package com.lj.api.v1.c;

import com.lj.api.common.CodeMsg;
import com.lj.api.common.CommUtils;
import com.lj.api.common.Md5Encrypt;
import com.lj.api.common.Result;
import com.lj.api.conifg.URL;
import com.lj.api.tools.Qniu.QNiuImageSetting;
import com.lj.api.tools.Qniu.QNiuTools;
import com.lj.mcore.entity.Accessory;
import com.lj.mcore.entity.User;
import com.lj.mcore.service.IAccessoryService;
import com.lj.mcore.service.IUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * Created by Administrator on 2016/2/16.
 */
@RestController
public class ImageJsonVeiwAction {

    @Autowired
    IAccessoryService accessoryService;

    @Autowired
    IUserService userService;

    @RequestMapping({"/json/qNiuAppImageCallBack.htm"})
    public void appImageCallBack(HttpServletRequest request, HttpServletResponse response, String w, String h, String key, String size, String uid, String path){
        showParams(request);
        Accessory accessory = new Accessory();

        accessory.setAddTime(new Date());       //accessory.setExt((String) map.get("mime"));
        key.substring(0, path.lastIndexOf("/"));
        accessory.setInfo("http://" + QNiuTools.getScopeDomain() + "/");
        accessory.setPath(path.substring(0, path.lastIndexOf("/") + 1));
        accessory.setWidth(Integer.valueOf(w));
        accessory.setHeight(Integer.valueOf(h));
        accessory.setName(path.substring(path.lastIndexOf("/") + 1, path.length()));
        accessory.setSize(Float.valueOf(size));
        User user = userService.getObjById(Long.valueOf(uid));
        accessory.setUser(user);
        accessoryService.save(accessory);

        user.setPhoto(accessory);
        this.userService.update(user);
        Map map1 = new HashMap();
        map1.put("key",path);
        Map map11 = new HashMap();
        map11.put("key",path);
        map11.put("domain",accessory.getInfo());
        map11.put("width",w);
        map11.put("height",h);
        map11.put("accessoryId",accessory.getId());
        map11.put("url",accessory.getInfo()+accessory.getPath()+accessory.getName());
        map11.put("good_url",accessory.getInfo()+accessory.getPath()+accessory.getName()+QNiuImageSetting.USER_IMAGE_SETTING);
        map1.put("payload", JSONObject.fromObject(map11));

        try {
            response.setContentType("text/plain");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.fromObject(map1));
            System.out.println(JSONObject.fromObject(map1).toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping({"/json/qNiuAppMap3CallBack.htm"})
    public void qNiuAppMap3CallBack(HttpServletRequest request, HttpServletResponse response,String w,String h,String key,String size,String uid,String path,String time){
        System.out.println("mp3--七牛上传MP3通知" + uid);
        Accessory accessory = new Accessory();
        String[] infos = uid.split(",");
        accessory.setAddTime(new Date());
        //accessory.setExt((String) map.get("mime"));
        key.substring(0, path.lastIndexOf("/"));
        accessory.setInfo("http://" + QNiuTools.getScopeDomain() + "/");
        accessory.setPath(path.substring(0, path.lastIndexOf("/") + 1));
        accessory.setWidth(Integer.valueOf(CommUtils.null2Int(w)));
        accessory.setHeight(Integer.valueOf(CommUtils.null2Int(h)));
        accessory.setName(path.substring(path.lastIndexOf("/") + 1, path.length()));
        accessory.setSize(Float.valueOf(size));
        accessory.setTime(CommUtils.null2String(infos[1]));
        accessory.setExt("mp3");
        User user = userService.getObjById(Long.valueOf(infos[0]));
        accessory.setUser(user);
        accessoryService.save(accessory);

        Map map1 = new HashMap();
        map1.put("key",path);
        Map map11 = new HashMap();
        map11.put("key",path);
        map11.put("domain",accessory.getInfo());
        map11.put("width",CommUtils.null2String(w));
        map11.put("height",CommUtils.null2String(h));
        map11.put("accessoryId",accessory.getId());
        map11.put("url",accessory.getInfo()+accessory.getPath()+accessory.getName());
        map11.put("good_url",accessory.getInfo()+accessory.getPath()+accessory.getName()+ QNiuImageSetting.USER_IMAGE_SETTING);
        map1.put("payload", JSONObject.fromObject(map11));

        try {
            response.setContentType("text/plain");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.fromObject(map1));
            System.out.println(JSONObject.fromObject(map1).toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping({"/json/qNiuAppCommentImageCallBack.htm"})
    public void appCommentImageCallBack(HttpServletRequest request, HttpServletResponse response,String w,String h,String key,String size,String uid,String path,String time,String fileName){
        showParams(request);
        Accessory accessory = new Accessory();

        accessory.setAddTime(new Date());
        //accessory.setExt((String) map.get("mime"));
        key.substring(0, path.lastIndexOf("/"));
        accessory.setInfo("http://" + QNiuTools.getScopeDomain() + "/");

        accessory.setPath(path.substring(0, path.lastIndexOf("/") + 1));
        accessory.setWidth(Integer.valueOf(CommUtils.null2Int(w)));
        accessory.setHeight(Integer.valueOf(CommUtils.null2Int(h)));
        accessory.setName(path.substring(path.lastIndexOf("/") + 1, path.length()));
        accessory.setSize(Float.valueOf(size));
        if (uid!=null && !uid.equals("")) {
            User user = userService.getObjById(Long.valueOf(uid));
            accessory.setUser(user);
        }
        accessory.setFileName(fileName);
        accessoryService.save(accessory);

        Map map1 = new HashMap();
        map1.put("key",path);
        Map map11 = new HashMap();
        map11.put("key",path);
        map11.put("domain",accessory.getInfo());
        map11.put("width",CommUtils.null2String(w));
        map11.put("height",CommUtils.null2String(h));
        map11.put("accessoryId",accessory.getId());
        map11.put("url",accessory.getInfo()+accessory.getPath()+accessory.getName());
        map11.put("good_url",accessory.getInfo()+accessory.getPath()+accessory.getName()+QNiuImageSetting.USER_IMAGE_SETTING);
        map1.put("payload", JSONObject.fromObject(map11));

        try {
            response.setContentType("text/plain");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.fromObject(map1));
            System.out.println(JSONObject.fromObject(map1).toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping({"/json/getAppImagesUpToken.htm"})
    public String getAppImagesUpToken(HttpServletRequest request, HttpServletResponse response,String buffix,String func){
        Map map = new HashMap();
        String key = QNiuTools.getKeyByName("img")+"."+buffix;
        String token = QNiuTools.getAppImagesUpToken(key,buffix,func);
        map.put("key", key);
        map.put("token", token);
        /*CommonUtil.renderJson(response, MapUtil.setRequestCode(ResultCode.SUCCESS.getCode(), list, "成功！"));*/
        return Result.ok(map);
    }

    @RequestMapping({"/json/getAppUpToken.htm"})
    public void getAppUpToken(HttpServletRequest request, HttpServletResponse response,String buffix,String func){
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
        List list = new ArrayList();
        Map map = new HashMap();

        String key = QNiuTools.getKeyByName(buffix) + "." + buffix;
        String token = QNiuTools.getAppImagesUpToken(key, buffix, func);
        map.put("key", key);
        map.put("token", token);
        list.add(map);
        System.out.println(net.sf.json.JSONArray.fromObject(list));
        /*CommonUtil.renderJson(response, MapUtil.setRequestCode(ResultCode.SUCCESS.getCode(), list, "成功！"));*/
        Result.ok(list);
    }


    @RequestMapping({"/json/getAppVideoUpToken.htm"})
    public void getAppVideoUpToken(HttpServletRequest request, HttpServletResponse response,String buffix,String func){
        List list = new ArrayList();
        Map map = new HashMap();
        String key = QNiuTools.getKeyByName("mp3")+"."+buffix;
        String token = QNiuTools.getAppImagesUpToken(key,buffix,func);
        map.put("key", key);
        map.put("token", token);
        list.add(map);
        Result.ok(list);
    }

    /**
     * s
     * @param request
     * @param response
     * @param buffix
     * @param type
     */
    @RequestMapping({"/json/getVideoUpTokenMap4V2.htm"})
    public void getVideoUpTokenMap4V2(HttpServletRequest request, HttpServletResponse response, String buffix,String type,String videoSecond){
        List list = new ArrayList();
        Map map = new HashMap();
        String key = QNiuTools.getKeyByName("mp4")+"."+buffix;
        String token =QNiuTools.getAppVideoToken(key,type,videoSecond);
        map.put("key", key);
        map.put("token", token);
        map.put("size",150*1024*1024);
        list.add(map);
        Result.ok(list);
    }

    @RequestMapping({"/json/getVideoUpTokenMap4.htm"})
    public void getVideoUpTokenMap4(HttpServletRequest request, HttpServletResponse response, String buffix,String type){
        List list = new ArrayList();
        Map map = new HashMap();
        String key = QNiuTools.getKeyByName("mp4")+"."+buffix;
        String token =QNiuTools.getAppVideoToken(key, type);
        map.put("key", key);
        map.put("token", token);
        list.add(map);
        Result.ok(list);
    }

    @RequestMapping({"/json/getVideoUrl.htm"})
    public void getVideoUrl(HttpServletResponse response, String aid,String type,String ts,String uid){
        List list=new ArrayList();
        if (StringUtils.isBlank(aid)||StringUtils.isBlank(type)||StringUtils.isBlank(ts)||StringUtils.isBlank(uid)){
            /*CommonUtil.renderJson(response, MapUtil.setRequestCode(ResultCode.ERROR.getCode(), list, "缺少参数"));*/
            Result.fail(CodeMsg.PARAMETER_ISNULL);
        }
        User user=userService.getObjById(Long.parseLong(uid));
        String phoneStr = user.getUsername().trim()+ URL.SMS_SECRET;
        String secet = Md5Encrypt.md5Phone(phoneStr);
        if (!ts.equals(secet)){
            /*CommonUtil.renderJson(response, MapUtil.setRequestCode(ResultCode.ERROR.getCode(), list, "非法请求"));*/
            Result.fail(CodeMsg.PARAMETER_ISNULL);
        }
        Accessory accessory=accessoryService.getObjById(Long.parseLong(aid));
        if (accessory==null){
            /*CommonUtil.renderJson(response, MapUtil.setRequestCode(ResultCode.ERROR.getCode(), list, "参数错误"));*/
            Result.fail(CodeMsg.ILLEGAL_PARAMS);
        }
        String url=accessory.getInfo()+accessory.getPath()+accessory.getName();
        if (type.equals("1")){
            url=QNiuTools.voucherUrl(url,Long.parseLong(accessory.getTime()));
        }
        list.add(url);
        Result.ok(list);
    }

    private void showParams(HttpServletRequest request) {
        Map map = new HashMap();
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();

            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length == 1) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    map.put(paramName, paramValue);
                }
            }
        }

        Set<Map.Entry<String, String>> set = map.entrySet();
        System.out.println("------------------------------");
        for (Map.Entry entry : set) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
        System.out.println("------------------------------");
    }


    @RequestMapping({"/json/qNiuAppMap4CallBack.htm"})
    public void qNiuAppMap4CallBack(HttpServletRequest request, HttpServletResponse response,String w,String h,String key,String size,String uid,String path,String persistentId){
        String q = request.getQueryString();


        System.out.println("mp4--七牛上传MP4通知"+uid);
        Accessory accessory = new Accessory();
        String[] infos = uid.split(",");
        accessory.setAddTime(new Date());
        //accessory.setExt((String) map.get("mime"));
        key.substring(0, path.lastIndexOf("/"));
        accessory.setInfo("http://" + QNiuTools.getScopeDomain() + "/");
        accessory.setPath(path.substring(0, path.lastIndexOf("/") + 1));
        accessory.setWidth(Integer.valueOf(CommUtils.null2Int(w)));
        accessory.setHeight(Integer.valueOf(CommUtils.null2Int(h)));
        accessory.setName(path.substring(path.lastIndexOf("/") + 1, path.length()));
        accessory.setSize(Float.valueOf(size));
        accessory.setTime(CommUtils.null2String(infos[1]));
        accessory.setExt("mp4");
        User user = userService.getObjById(Long.valueOf(infos[0]));
        accessory.setUser(user);
        accessoryService.save(accessory);

        Map map1 = new HashMap();
        map1.put("key",path);
        Map map11 = new HashMap();
        map11.put("key",path);
        map11.put("domain",accessory.getInfo());
        map11.put("width", CommUtils.null2String(w));
        map11.put("height",CommUtils.null2String(h));
        map11.put("accessoryId",accessory.getId());
        map11.put("url",accessory.getInfo()+accessory.getPath()+accessory.getName());
        map11.put("good_url",accessory.getInfo()+accessory.getPath()+accessory.getName()+QNiuImageSetting.USER_IMAGE_SETTING);
        map1.put("payload", JSONObject.fromObject(map11));

        try {
            response.setContentType("text/plain");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.fromObject(map1));
            System.out.println(JSONObject.fromObject(map1).toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping({"/json/qNiuAppMp4ImageCallBack.htm"})
    public void qNiuAppMp4ImageCallBack(HttpServletRequest request, HttpServletResponse response,String w,String h,String key,String size,String uid,String path,String persistentId,String loadType){

        System.out.println("mp4--七牛上传MP4通知"+uid);
        Accessory accessory = new Accessory();
        String[] infos = uid.split(",");
        accessory.setAddTime(new Date());
        //accessory.setExt((String) map.get("mime"));
        key.substring(0, path.lastIndexOf("/"));
        accessory.setInfo("http://" + QNiuTools.getScopeDomain() + "/");
        accessory.setPath(path.substring(0, path.lastIndexOf("/") + 1));
        accessory.setWidth(Integer.valueOf(CommUtils.null2Int(w)));
        accessory.setHeight(Integer.valueOf(CommUtils.null2Int(h)));
        accessory.setName(path.substring(path.lastIndexOf("/") + 1, path.length()));
        accessory.setSize(Float.valueOf(size));
        accessory.setTime(CommUtils.null2String(infos[1]));
        accessory.setExt("mp4");
        User user = userService.getObjById(Long.valueOf(infos[0]));
        accessory.setUser(user);
        accessoryService.save(accessory);

        Map map1 = new HashMap();
        map1.put("key",path);
        Map map11 = new HashMap();
        map11.put("key",path);
        map11.put("domain",accessory.getInfo());
        map11.put("width",CommUtils.null2String(w));
        map11.put("height",CommUtils.null2String(h));
        map11.put("video_id",accessory.getId());
        String videoSecond =CommUtils.null2String(infos[1]);
        double second =0.0;
        if(videoSecond!=null && !videoSecond.equals("")){
            if (CommUtils.null2Double(videoSecond)<=1.0){
                second=CommUtils.null2Double(videoSecond);
            }else {
                second = CommUtils.null2Double(videoSecond)/2;
                second = (double) (Math.round(second * 10) / 10.0);
            }
        }
        map11.put("img_url",accessory.getInfo()+accessory.getPath()+accessory.getName()+"?vframe/jpg/offset/"+second);
        map11.put("video_url",accessory.getInfo()+accessory.getPath()+accessory.getName());
        map1.put("payload", JSONObject.fromObject(map11));

        try {
            response.setContentType("text/plain");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.fromObject(map1).toString());
            System.out.println(JSONObject.fromObject(map1).toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
